const GROUP = ["World Cup, Group A", "World Cup, Group B", "World Cup, Group C", "World Cup, Group D", "World Cup, Group E", "World Cup, Group F", "World Cup, Group G", "World Cup, Group H"];
const LEVELS = ["Group Stage", "Final!", "Semi-Final", "Quarter-Final", "1/8"];
/**
 * This function is called ONLY if the user does not have the mapping in his local storage
 */
function requestNewMapping(i_level) {
    var request = false;
    var result = null;
    request = new XMLHttpRequest();
    if (request) {
        request.open("GET", "newMappings/" + i_level);
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                result = JSON.parse(request.responseText);
                if (result == null) {
                    console.log("Problem getting mapping for level - " + i_level);
                } else {
                    //Go Over all the matches and store in the localstorage for mapping
                    for (var i = 0; i < result.length; i++) {
                        localStorage.setItem(result[i].match_id, result[i].teams);

                        //In case of group stage - I also want to map between Group and the 4 teams (For qualifiers)
                        if (i_level == 0) {
                            //TODO: Based on @yahav's fix

                        }
                    }

                }

            }
        };
        request.setRequestHeader('content-type', 'application/json');
        request.send(null);
    }
}

/**
 * Gets the mapping of Qualifiers - should happen on init
 * result should come back as array of {groupName:<value> , teams:[]}
 */
function requestQualifiersMapping() {
    //Get the mapping only if doesn't exist - this should only happen the first time
    if (localStorage.getItem("World Cup, Group A") == null) {
        var request = false;
        var result = null;
        request = new XMLHttpRequest();
        if (request) {
            request.open("GET", "newQualifiersMapping/");
            request.onreadystatechange = function() {
                if (request.readyState == 4 && request.status == 200) {
                    result = JSON.parse(request.responseText);
                    for (var i = 0; i < result.length; i++) {
                        localStorage.setItem(result[i].groupName, result[i].teams);
                    }

                }
            };
            request.setRequestHeader('content-type', 'application/json');
            request.send(null);
        }
    }

}

/**
 * Gets the users from server - and sends to tableBuilder.buildUserTable
 */
function getUsers() {
    var request = false;
    var result = null;
    request = new XMLHttpRequest();
    if (request) {
        request.open("GET", "users/" + localStorage.getItem('collection'));
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                result = JSON.parse(request.responseText);
                buildUserTable(result);

            }
        };
        request.setRequestHeader('content-type', 'application/json');
        request.send(null);
    }
}

/**
 * Gets all the users from all the collections and sends to buildWorldTable(result)
 */
function getWorldUsers() {
    //Empty the rule div
    $('#rulesDiv').html("");
    document.getElementById('groupStageTab').innerHTML = "Group Stage";

    checkBetStatus();
    var request = false;
    var result = null;
    request = new XMLHttpRequest();
    if (request) {
        request.open("GET", "usersWorld/");
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                result = JSON.parse(request.responseText);
                buildWorldTable(result);

            }
        };
        request.setRequestHeader('content-type', 'application/json');
        request.send(null);
    }
}

/**
 * Gets the users from server - and sends to tableBuilder.buildUserTable
 */
function getKnockoutBets(i_level) {
    //Clear the Rules Div
    $('#rulesDiv').html("");
    //Check to see if this level is OPEN before going to server
    var navBar = "header" + i_level;
    if (!$('#' + navBar).hasClass('disabled')) {
        var request = false;
        var result = null;
        request = new XMLHttpRequest();
        if (request) {
            request.open("GET", "getLevel/" + i_level + "/" + localStorage.getItem('collection'));
            request.onreadystatechange = function() {
                if (request.readyState == 4 && request.status == 200) {
                    result = JSON.parse(request.responseText);
                    //console.log("Bets have arrived");
                    buildKnockoutBetTable(i_level, result);

                }
            };
            request.setRequestHeader('content-type', 'application/json');
            request.send(null);
        }
    } else {
        //This is disabled - show something!!
        $("#GroupAndKnockoutTableDiv").html("<div style='margin-top:150px;text-align:right;font-family:hebrewFont;font-size:40px'><p>הלו להירגע</p><p>כאן תופיע טבלת ההימורים של כולם לשלב הזה - כרגע זה מידע חסוי</p></div>");
    }

}

/**
 * This function is called only when it is time to enable a new header
 * @param level to enable
 */
function levelHeaderEnabler(i_level) {

    //Special case - group stage
    if (i_level == 0) {
        var navBar = "header" + i_level;
        $('#' + navBar).removeClass('disabled');
    } else {
        for (var i = LEVELS.length - 1; i >= i_level; i--) {
            var navBar = "header" + i;
            $('#' + navBar).removeClass('disabled');
        }
    }
    //Enable Tournament Bets

}

/**
 * Gets the users from server - and sends to tableBuilder.buildUserTable
 */
function getGroupBets(groupName) {
    checkBetStatus();
    //Clear the Rules Div
    $('#rulesDiv').html("");
    var navBar = "header" + 0;
    if (!$('#' + navBar).hasClass('disabled')) {
        document.getElementById('groupStageTab').innerHTML = "Group " + groupName + "<strong class='caret'></strong>";
        var request = false;
        var result = null;
        request = new XMLHttpRequest();
        if (request) {
            request.open("GET", "/getGroupStage/" + groupName + "/" + localStorage.getItem('collection'));
            request.onreadystatechange = function() {
                if (request.readyState == 4 && request.status == 200) {
                    result = JSON.parse(request.responseText);
                    console.log("Bets have arrived");
                    getQualifiersForGroup(groupName, function(qualifiersResult) {
                        buildGroupBetTable(groupName, result, qualifiersResult);
                    });

                }
            };
            request.setRequestHeader('content-type', 'application/json');
            request.send(null);
        }
    } else {
        //Disbaled - show something!
        $("#GroupAndKnockoutTableDiv").html("<div style='margin-top:150px;text-align:right;font-family:hebrewFont;font-size:40px'><p>הלו להירגע</p><p>כאן תופיע טבלת ההימורים של כולם לשלב הזה - כרגע זה מידע חסוי</p></div>");

    }
}

/**
 * Gets the main tournament bets from the users
 * and calls the tableBuilder to build the 'others' table
 */
function getTournamentBets() {
    //$("#GroupAndKnockoutTableDiv").html("<div style='margin-top:150px;text-align:right;font-family:hebrewFont;font-size:40px'><p>הלו להירגע</p><p>כאן תופיע טבלת ההימורים של כולם לשלב הזה - כרגע זה מידע חסוי</p></div>");

    //Empty the rule div
    $('#rulesDiv').html("");
    document.getElementById('groupStageTab').innerHTML = "Group Stage";

    var request = false;
    var result = null;
    request = new XMLHttpRequest();
    if (request) {
        request.open("GET", "/tournamentBets/" + localStorage.getItem('collection'));
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                result = JSON.parse(request.responseText);
                buildOthersTable(result);

            }
        };
        request.setRequestHeader('content-type', 'application/json');
        request.send(null);
    }
}

function changeName() {
    var firstName = $('#inputChangeFirstName').val();
    var lastName = $('#inputChangeLastName').val();

    if (firstName.length < 2 || lastName < 2) {
        //Illegal name, too short
        alert("Name too short");
    } else {
        var fixedName = capitalizeName(firstName, lastName);
        var request = false;
        var result = null;
        request = new XMLHttpRequest();
        if (request) {
            request.open("GET", "/usersNameChange/" + fixedName + "/" + localStorage.getItem('name'));
            request.onreadystatechange = function() {
                if (request.readyState == 4 && request.status == 200) {
                    result = JSON.parse(request.responseText);
                    localStorage.setItem('name', fixedName);
                    getUsers();

                }
            };
            request.setRequestHeader('content-type', 'application/json');
            request.send(null);
        }

    }

}

/**
 * Fixes the name
 */
function capitalizeName(first, last) {
    first = first.toLowerCase();
    last = last.toLowerCase();
    var firstCorrect = first.charAt(0).toUpperCase() + first.slice(1);
    var lastCorrect = last.charAt(0).toUpperCase() + last.slice(1);

    return firstCorrect + " " + lastCorrect;
}

/**
 * Gets the player profile - where he can see ALL of his bets
 */
function profile() {
    var request = false;
    var result = null;
    request = new XMLHttpRequest();
    if (request) {
        request.open("GET", "/usersProfile/" + localStorage.getItem('name'));
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                result = JSON.parse(request.responseText);
                if (result != null) {
                    buildProfileTable(result);

                } else {
                    //Problem getting user profile - maybe doesn't exist?

                }

            }
        };
        request.setRequestHeader('content-type', 'application/json');
        request.send(null);
    }
}

/**
 * Gets the users from server - and sends to tableBuilder.buildUserTable
 */
function getQualifiersForGroup(groupName, callback) {
    var request = false;
    var result = null;
    request = new XMLHttpRequest();
    if (request) {
        request.open("GET", "/getQualifiers/" + groupName + "/" + localStorage.getItem('collection'));
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                result = JSON.parse(request.responseText);
                callback(result);

            }
        };
        request.setRequestHeader('content-type', 'application/json');
        request.send(null);
    }
}

/**
 * Posts the next game inside the #nextMatchesDiv
 * @param {Object} nextMatchesArray {match_id:<value> , date:<value>}
 */
function todayMatchesBuilder(i_date) {
    var request = false;
    var result = null;
    var html = "";
    request = new XMLHttpRequest();
    if (request) {
        request.open("GET", "/todaysMatches/" + i_date);
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                result = JSON.parse(request.responseText);

                //Iterate over this day's matches and write them in #nextMatchesDiv
                for (var i = 0; i < result.length; i++) {
                    html += "<h2 id='nextMatchSpan' class='text-center'><a href='#'>" + map(null, result[i].match_id).home + " vs " + map(null, result[i].match_id).away + "</a></h2>";
                }
                document.getElementById('nextMatchesDiv').innerHTML = html;

            }
        };
        request.setRequestHeader('content-type', 'application/json');
        request.send(null);
    }

}

/**
 * On arrival to index.html - check if to hide or show the next bet button (button default is hide!!!)
 */
function checkBetStatus() {
    var request = false;
    var result = null;
    var html = "";
    request = new XMLHttpRequest();
    if (request) {
        request.open("GET", "/checkBetStatus/");
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                result = JSON.parse(request.responseText);
                //var betStatus = result.betOpen;
                if ((result != null && result.betOpen)) {
                    //Show button + the time until closing
                    $('#levelToBetSpan').html("Place a bet On: " + LEVELS[result]);
                    //Write current betting Level in localstorage and use it later
                    localStorage.setItem('currentLevel', result.betLevel);

                    $('#placeABetButton').show();

                    //Open up tournmanet Bets
                    if (parseInt(result.betLevel) == 0) {
                        $('#tournBetButton').show();
                        $('#qualBetButton').show();
                    }

                } else {
                    //Betting status came back as false - no betting is allowed
                    levelHeaderEnabler(parseInt(result.betLevel));
                    localStorage.setItem('currentLevel', result.betLevel);
                    //console.log("No betting allowed");
                }
            }
        };
        request.setRequestHeader('content-type', 'application/json');
        request.send(null);
    }
}

/**
 * Calls the bet form builder
 */
function setupBettingPage() {
    checkBetStatus();
    document.getElementById('groupStageTab').innerHTML = "Group Stage";

    var request = false;
    var result = null;
    var html = "";
    request = new XMLHttpRequest();
    if (request) {
        request.open("GET", "/bettingPage/" + localStorage.getItem('name'));
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                result = JSON.parse(request.responseText);
                //Someone wants to open the group stage betting page
                if (result.level == 0) {
                    buildKnockoutBetForm(0, result.result[0].groups);

                }
                //Someone wants to open a knockout betting page
                else {
                    buildKnockoutBetForm(result.level, result.result.knockout);
                }
            }
        };
        request.setRequestHeader('content-type', 'application/json');
        request.send(null);
    }

}

/**
 * Especially for the tournament bets
 */
function setupTournBettingPage() {
    checkBetStatus();
    var request = false;
    var result = null;
    var html = "";
    request = new XMLHttpRequest();
    if (request) {
        request.open("GET", "/tournamentBets/" + localStorage.getItem('collection'));
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                result = JSON.parse(request.responseText);
                for (var i = 0; i < result.length; i++) {
                    if (result[i].name == localStorage.getItem('name')) {
                        buildTournBetForm(result[i]);

                    }
                };

            }
        };
        request.setRequestHeader('content-type', 'application/json');
        request.send(null);
    }
}

/**
 * Sends the form to the server
 * @param level that was bet on
 * @param matches array to run on the HTML to retrieve scores
 * @return array in the form of {match_id: <value> , score:[]}
 */
function submitKnockoutAndGroupBet(i_level, i_matchesString) {
    checkBetStatus();
    var submitArr = [];
    var winner = null;
    var matchesArray = i_matchesString.split("_");
    for (var i = 0; i < matchesArray.length - 1; i++) {
        var tempMatch = matchesArray[i];
        var scoreHome = $('#' + tempMatch + '_home').val();
        var scoreAway = $('#' + tempMatch + '_away').val();

        if (scoreAway < 0) {
            scoreAway = 0;
        }
        if (scoreHome < 0) {
            scoreHome = 0;
        }
        if (i_level == 0) {
            submitArr.push({
                match_id : tempMatch,
                score : [scoreHome, scoreAway],
            });
        } else {
            var winner = $('#' + tempMatch + '_winner option:selected').text();

            //TODO: Don't allow someone to bet a winner against the score @yahav

            submitArr.push({
                match_id : tempMatch,
                score : [scoreHome, scoreAway],
                winner : winner
            });
        }

    }
    var request = false;
    var result = null;
    var html = "";
    request = new XMLHttpRequest();
    if (request) {
        request.open("POST", "/submitKnockoutAndGroupBet/" + i_level + '/' + localStorage.getItem('name'));
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                result = JSON.parse(request.responseText);
                if (result == true) {

                    //Now bring the qualifiers Bet:
                    if (i_level == 0) {
                        document.getElementById('GroupAndKnockoutTableDiv').innerHTML = "";

                        //buildQualifiersBetForm();
                    } else {

                        document.getElementById('GroupAndKnockoutTableDiv').innerHTML = "";

                    }
                }
            }
        };

        request.setRequestHeader('content-type', 'application/json');
        request.send(JSON.stringify(submitArr));
    }

}

/**
 * Opens the match for this user (gets his name from LocalStorage)
 */
function openMatch(i_level, match_id) {
    var r = confirm("בטוח שאתה פותח?? איך דרך חזרה");
    if (r == true) {
        var name = localStorage.getItem('name');
        var request = false;
        var result = null;
        var html = "";
        request = new XMLHttpRequest();
        if (request) {
            request.open("GET", "/usersOpenMatch/" + match_id + '/' + name + '/' + i_level);
            request.onreadystatechange = function() {
                if (request.readyState == 4 && request.status == 200) {
                    result = JSON.parse(request.responseText);
                    if (result == true) {

                        //Refresh the betting page
                        getUsers();
                        setupBettingPage();

                    } else {
                        //Could not open game - not enough points!
                        //Setup popup text
                        $('#popupText').html("אין לך מספיק נקודות לפתוח ת'משחק");
                        window.location.href = "#modal-container-129013";
                        alert("You don't have enough points to open this game");
                    }
                }
            };

            request.setRequestHeader('content-type', 'application/json');
            request.send(null);
        }
    }

}

/**
 * Sends the server the qualifiers for this user
 * @return to the server: {groupName:<value> , rankedFirst:<value> , rankedSecond:<value>}
 */
function submitQualifiersBet() {
    var sendToServer = [];
    var sameName = false;
    for (var i = 0; i < GROUP.length; i++) {
        var trimmed = GROUP[i].split(' ')[3];
        //Iterate over groups and get the values that the user selected
        var rankedFirst = $('#' + trimmed + '_rankedFirst option:selected').text();
        var rankedSecond = $('#' + trimmed + '_rankedSecond option:selected').text();
        if (rankedFirst == rankedSecond) {
            //Mark this boolean
            sameName = true;
        }

        sendToServer.push({
            groupName : GROUP[i],
            rankedFirst : rankedFirst,
            rankedSecond : rankedSecond
        });

        //Remember his picked Choices?
        localStorage.setItem('qualifier' + trimmed, [rankedFirst, rankedSecond]);
    }
    if (!sameName) {
        //Means this player bet ok
        var request = false;
        var result = null;
        var html = "";
        request = new XMLHttpRequest();
        if (request) {
            request.open("POST", "/submitQualifiersBet/" + localStorage.getItem('name'));
            request.onreadystatechange = function() {
                if (request.readyState == 4 && request.status == 200) {
                    result = JSON.parse(request.responseText);
                    if (result == true) {

                        document.getElementById('GroupAndKnockoutTableDiv').innerHTML = "";

                    }
                }
            };

            request.setRequestHeader('content-type', 'application/json');
            request.send(JSON.stringify(sendToServer));
        }
    } else {
        //This player put the same team twice!
        alert("You bet on the same team twice!");
    }
}

function submitTournBet() {
    //Empty the rule div
    $('#rulesDiv').html("");
    checkBetStatus();
    var pickedChampion = $('#championSelect option:selected').text();
    var pickedKingOfAssists = $('#inputMvp option:selected').text();
    var pickedKingOfGoals = $('#inputKingOfGoals option:selected').val();
    var request = false;
    var result = null;
    var sendToServer = {
        champion : pickedChampion,
        kingOfAssists : pickedKingOfAssists,
        kingOfGoals : pickedKingOfGoals
    };
    request = new XMLHttpRequest();
    if (request) {
        request.open("POST", "/submitTournBet/" + localStorage.getItem('name'));
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                result = JSON.parse(request.responseText);
                if (result == true) {
                    //Now bring the qualifiers Bet:

                    //Show nothing on the screen
                    document.getElementById('GroupAndKnockoutTableDiv').innerHTML = "";
                }
            }
        };

        request.setRequestHeader('content-type', 'application/json');
        request.send(JSON.stringify(sendToServer));
    }
}

/**
 * Logs out the user - empties his localstorage name and collection, and sends him to login.html
 * Also needs to remove his collection name from the Server
 */
function logout() {

    localStorage.removeItem('name');

    window.location.href = './index.html';
}

function changeGroup() {
    var request = false;
    var result = null;
    var html = "";
    request = new XMLHttpRequest();
    if (request) {
        request.open("GET", "/userRemoveCollection/" + localStorage.getItem('name'));
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                result = JSON.parse(request.responseText);
            }
        };

        request.setRequestHeader('content-type', 'application/json');
        request.send(JSON.stringify(null));
    }
    localStorage.removeItem('collection');
    window.location.href = './gameLogin.html';
}

//Check if user exists in localstorage - if NOT - redirect to login.html
if (localStorage.getItem('name') == null) {
    window.location.href = './login.html';

} else if (localStorage.getItem('collection') == null) {
    window.location.href = './gameLogin.html';
} else {
    $(document).ready(function() {
        // $('#userNameSpan').html("Hey " + localStorage.getItem('name').split(' ')[0] + ",");
        // $('#collectionNameSpan').html(localStorage.getItem('collection'));
        getUsers();
        // todayMatchesBuilder(new Date());
        requestQualifiersMapping();
        //This checks if to hide or show the "place a bet" button
        //Hide the button and THEN CHECK
        $('#placeABetButton').hide();
        $('#tournBetButton').hide();
        $('#qualBetButton').hide();
        checkBetStatus();

        var currLevel = localStorage.getItem('currentLevel');
        if (currLevel == null) {
            requestNewMapping(0);
        } else {
            requestNewMapping(parseInt(currLevel));
        }

        //Open all headers up to this current betting level (not including)
        var currentLevel = localStorage.getItem('currentLevel');
        if (parseInt(currentLevel) != 0 && currentLevel != null) {
            levelHeaderEnabler(0);
            levelHeaderEnabler(parseInt(currentLevel) + 1);
        }

    });

}

